{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nDeploy Pretrained Vision Detection Model from Darknet on VTA\n============================================================\n**Author**: `Hua Jiang <https://github.com/huajsj>`_\n\nThis tutorial provides an end-to-end demo, on how to run Darknet YoloV3-tiny\ninference onto the VTA accelerator design to perform Image detection tasks.\nIt showcases Relay as a front end compiler that can perform quantization (VTA\nonly supports int8/32 inference) as well as graph packing (in order to enable\ntensorization in the core) to massage the compute graph for the hardware target.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Install dependencies\n--------------------\nTo use the autotvm package in tvm, we need to install some extra dependencies.\n(change \"3\" to \"2\" if you use python2):\n\n.. code-block:: bash\n\npip3 install \"Pillow<7\"\n\nYOLO-V3-tiny Model with Darknet parsing have dependancy with CFFI and CV2 library,\nwe need to install CFFI and CV2 before executing this script.\n\npip3 install \"Pillow<7\"\n\npip3 install cffi\npip3 install opencv-python\n\nNow return to the python code. Import packages.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from __future__ import absolute_import, print_function\n\nimport sys\nimport os\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tvm\nimport vta\nfrom tvm import rpc, autotvm, relay\nfrom tvm.relay.testing import yolo_detection, darknet\nfrom tvm.relay.testing.darknet import __darknetffi__\nfrom tvm.contrib import graph_executor, utils\nfrom tvm.contrib.download import download_testdata\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\n\n# Make sure that TVM was compiled with RPC=1\nassert tvm.runtime.enabled(\"rpc\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Download yolo net configure file, weight file, darknet library file based on\nModel Name\n----------------------------------------------------------------------------\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "MODEL_NAME = \"yolov3-tiny\"\nREPO_URL = \"https://github.com/dmlc/web-data/blob/main/darknet/\"\n\ncfg_path = download_testdata(\n    \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + MODEL_NAME + \".cfg\" + \"?raw=true\",\n    MODEL_NAME + \".cfg\",\n    module=\"darknet\",\n)\nweights_path = download_testdata(\n    \"https://pjreddie.com/media/files/\" + MODEL_NAME + \".weights\" + \"?raw=true\",\n    MODEL_NAME + \".weights\",\n    module=\"darknet\",\n)\n\nif sys.platform in [\"linux\", \"linux2\"]:\n    darknet_lib_path = download_testdata(\n        REPO_URL + \"lib/\" + \"libdarknet2.0.so\" + \"?raw=true\", \"libdarknet2.0.so\", module=\"darknet\"\n    )\nelif sys.platform == \"darwin\":\n    darknet_lib_path = download_testdata(\n        REPO_URL + \"lib_osx/\" + \"libdarknet_mac2.0.so\" + \"?raw=true\",\n        \"libdarknet_mac2.0.so\",\n        module=\"darknet\",\n    )\nelse:\n    raise NotImplementedError(\"Darknet lib is not supported on {} platform\".format(sys.platform))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Download yolo categories and illustration front.\n------------------------------------------------\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coco_path = download_testdata(\n    REPO_URL + \"data/\" + \"coco.names\" + \"?raw=true\", \"coco.names\", module=\"data\"\n)\nfont_path = download_testdata(\n    REPO_URL + \"data/\" + \"arial.ttf\" + \"?raw=true\", \"arial.ttf\", module=\"data\"\n)\nwith open(coco_path) as f:\n    content = f.readlines()\nnames = [x.strip() for x in content]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Define the platform and model targets.\n--------------------------------------\nExecute on CPU vs. VTA, and define the model.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n# Set ``device=arm_cpu`` to run inference on the CPU\n# or ``device=vta`` to run inference on the FPGA.\ndevice = \"vta\"\ntarget = env.target if device == \"vta\" else env.target_vta_cpu\n\npack_dict = {\n    \"yolov3-tiny\": [\"nn.max_pool2d\", \"cast\", 4, 186],\n}\n\n# Name of Darknet model to compile\n# The ``start_pack`` and ``stop_pack`` labels indicate where\n# to start and end the graph packing relay pass: in other words\n# where to start and finish offloading to VTA.\n# the number 4 indicate the the ``start_pack`` index is 4, the\n# number 186 indicate the ``stop_pack index`` is 186, by using\n# name and index number, here we can located to correct place\n# where to start/end when there are multiple ``nn.max_pool2d``\n# or ``cast``, print(mod.astext(show_meta_data=False)) can help\n# to find operator name and index information.\nassert MODEL_NAME in pack_dict"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Obtain an execution remote.\n---------------------------\nWhen target is 'pynq' or other FPGA backend, reconfigure FPGA and runtime.\nOtherwise, if target is 'sim', execute locally.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "if env.TARGET not in [\"sim\", \"tsim\"]:\n    # Get remote from tracker node if environment variable is set.\n    # To set up the tracker, you'll need to follow the \"Auto-tuning\n    # a convolutional network for VTA\" tutorial.\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    # Otherwise if you have a device you want to program directly from\n    # the host, make sure you've set the variables below to the IP of\n    # your board.\n    device_host = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\n    device_port = os.environ.get(\"VTA_RPC_PORT\", \"9091\")\n    if not tracker_host or not tracker_port:\n        remote = rpc.connect(device_host, int(device_port))\n    else:\n        remote = autotvm.measure.request_remote(\n            env.TARGET, tracker_host, int(tracker_port), timeout=10000\n        )\n    # Reconfigure the JIT runtime and FPGA.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    reconfig_start = time.time()\n    vta.reconfig_runtime(remote)\n    vta.program_fpga(remote, bitstream=None)\n    reconfig_time = time.time() - reconfig_start\n    print(\"Reconfigured FPGA and RPC runtime in {0:.2f}s!\".format(reconfig_time))\n\n# In simulation mode, host the RPC server locally.\nelse:\n    remote = rpc.LocalSession()\n\n# Get execution context from remote\nctx = remote.ext_dev(0) if device == \"vta\" else remote.cpu(0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Build the inference graph executor.\n-----------------------------------\nUsing Darknet library load downloaded vision model and compile with Relay.\nThe compilation steps are:\n\n1. Front end translation from Darknet into Relay module.\n2. Apply 8-bit quantization: here we skip the first conv layer,\n   and dense layer which will both be executed in fp32 on the CPU.\n3. Perform graph packing to alter the data layout for tensorization.\n4. Perform constant folding to reduce number of operators (e.g. eliminate batch norm multiply).\n5. Perform relay build to object file.\n6. Load the object file onto remote (FPGA device).\n7. Generate graph executor, `m`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Load pre-configured AutoTVM schedules\nwith autotvm.tophub.context(target):\n    net = __darknetffi__.dlopen(darknet_lib_path).load_network(\n        cfg_path.encode(\"utf-8\"), weights_path.encode(\"utf-8\"), 0\n    )\n    dshape = (env.BATCH, net.c, net.h, net.w)\n    dtype = \"float32\"\n\n    # Measure build start time\n    build_start = time.time()\n\n    # Start front end compilation\n    mod, params = relay.frontend.from_darknet(net, dtype=dtype, shape=dshape)\n\n    if target.device_name == \"vta\":\n        # Perform quantization in Relay\n        # Note: We set opt_level to 3 in order to fold batch norm\n        with tvm.transform.PassContext(opt_level=3):\n            with relay.quantize.qconfig(\n                global_scale=23.0,\n                skip_conv_layers=[0],\n                store_lowbit_output=True,\n                round_for_shift=True,\n            ):\n                mod = relay.quantize.quantize(mod, params=params)\n            # Perform graph packing and constant folding for VTA target\n            mod = graph_pack(\n                mod[\"main\"],\n                env.BATCH,\n                env.BLOCK_OUT,\n                env.WGT_WIDTH,\n                start_name=pack_dict[MODEL_NAME][0],\n                stop_name=pack_dict[MODEL_NAME][1],\n                start_name_idx=pack_dict[MODEL_NAME][2],\n                stop_name_idx=pack_dict[MODEL_NAME][3],\n            )\n    else:\n        mod = mod[\"main\"]\n\n    # Compile Relay program with AlterOpLayout disabled\n    with vta.build_config(disabled_pass={\"AlterOpLayout\"}):\n        lib = relay.build(mod, target=target, params=params, target_host=env.target_host)\n\n    # Measure Relay build time\n    build_time = time.time() - build_start\n    print(MODEL_NAME + \" inference graph built in {0:.2f}s!\".format(build_time))\n\n    # Send the inference library over to the remote RPC server\n    temp = utils.tempdir()\n    lib.export_library(temp.relpath(\"graphlib.tar\"))\n    remote.upload(temp.relpath(\"graphlib.tar\"))\n    lib = remote.load_module(\"graphlib.tar\")\n\n    # Graph executor\n    m = graph_executor.GraphModule(lib[\"default\"](ctx))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Perform image detection inference.\n----------------------------------\nWe run detect on an downloaded image\nDownload test image\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "[neth, netw] = dshape[2:]\ntest_image = \"person.jpg\"\nimg_url = REPO_URL + \"data/\" + test_image + \"?raw=true\"\nimg_path = download_testdata(img_url, test_image, \"data\")\ndata = darknet.load_image(img_path, neth, netw).transpose(1, 2, 0)\n\n# Prepare test image for inference\nplt.imshow(data)\nplt.show()\ndata = data.transpose((2, 0, 1))\ndata = data[np.newaxis, :]\ndata = np.repeat(data, env.BATCH, axis=0)\n\n# Set the network parameters and inputs\nm.set_input(\"data\", data)\n\n# Perform inference and gather execution statistics\n# More on: :py:method:`tvm.runtime.Module.time_evaluator`\nnum = 4  # number of times we run module for a single measurement\nrep = 3  # number of measurements (we derive std dev from this)\ntimer = m.module.time_evaluator(\"run\", ctx, number=num, repeat=rep)\n\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n    timer()\n    sim_stats = simulator.stats()\n    print(\"\\nExecution statistics:\")\n    for k, v in sim_stats.items():\n        # Since we execute the workload many times, we need to normalize stats\n        # Note that there is always one warm up run\n        # Therefore we divide the overall stats by (num * rep + 1)\n        print(\"\\t{:<16}: {:>16}\".format(k, v // (num * rep + 1)))\nelse:\n    tcost = timer()\n    std = np.std(tcost.results) * 1000\n    mean = tcost.mean * 1000\n    print(\"\\nPerformed inference in %.2fms (std = %.2f) for %d samples\" % (mean, std, env.BATCH))\n    print(\"Average per sample inference time: %.2fms\" % (mean / env.BATCH))\n\n# Get detection results from out\nthresh = 0.5\nnms_thresh = 0.45\ntvm_out = []\nfor i in range(2):\n    layer_out = {}\n    layer_out[\"type\"] = \"Yolo\"\n    # Get the yolo layer attributes (n, out_c, out_h, out_w, classes, total)\n    layer_attr = m.get_output(i * 4 + 3).numpy()\n    layer_out[\"biases\"] = m.get_output(i * 4 + 2).numpy()\n    layer_out[\"mask\"] = m.get_output(i * 4 + 1).numpy()\n    out_shape = (layer_attr[0], layer_attr[1] // layer_attr[0], layer_attr[2], layer_attr[3])\n    layer_out[\"output\"] = m.get_output(i * 4).numpy().reshape(out_shape)\n    layer_out[\"classes\"] = layer_attr[4]\n    tvm_out.append(layer_out)\n    thresh = 0.560\n\n# Show detection results\nimg = darknet.load_image_color(img_path)\n_, im_h, im_w = img.shape\ndets = yolo_detection.fill_network_boxes((netw, neth), (im_w, im_h), thresh, 1, tvm_out)\nlast_layer = net.layers[net.n - 1]\nyolo_detection.do_nms_sort(dets, last_layer.classes, nms_thresh)\nyolo_detection.draw_detections(font_path, img, dets, thresh, names, last_layer.classes)\nplt.imshow(img.transpose(1, 2, 0))\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}